// ABP框架与Swagger UI集成脚本
var abp = abp || {};
(function () {
    // ABP特定的Swagger扩展

    // 添加ABP认证token到请求
    var authTokenCookieName = "ABP.AuthToken";
    
    function getCookieValue(key) {
        var equalities = document.cookie.split('; ');
        for (var i = 0; i < equalities.length; i++) {
            if (!equalities[i]) {
                continue;
            }

            var splitted = equalities[i].split('=');
            if (splitted.length != 2) {
                continue;
            }

            if (decodeURIComponent(splitted[0]) === key) {
                return decodeURIComponent(splitted[1] || '');
            }
        }

        return null;
    }

    function getAuthToken() {
        return getCookieValue(authTokenCookieName);
    }

    // 在Swagger UI加载后执行
    window.addEventListener('load', function() {
        var authToken = getAuthToken();
        if (!authToken) {
            console.log("没有发现认证令牌！");
            return;
        }

        console.log("发现认证令牌，将自动添加到请求。");

        // 添加请求拦截器
        if (window.ui && window.ui.getSystem) {
            var system = window.ui.getSystem();
            if (system && system.plugins && system.plugins.statePlugins && system.plugins.statePlugins.auth) {
                var preauthorizeApiKey = system.plugins.statePlugins.auth.actions.preauthorizeApiKey;
                if (preauthorizeApiKey) {
                    preauthorizeApiKey("Bearer", authToken);
                }
            }
        }
    });
})();